const validate = require('../../utils/validate')
const common = require('../../utils/common')
const store = require('../../utils/store')

Page({
  data: {
    formData: {
      realName: '',
      idNo: '',
      mobile: '',
      wechatNo: '',
      bankCardNo: '',
      bankCardOwner: '',
    },
    isSubmitEnable: false,
    edit: 0,
  },
  onLoad: function ({ edit }) {
    if (edit == 1) {
      this.setData({
        edit,
      })
      const payload = store.getStore('editStore')
      if (!payload) return
      this.initFormData(payload)
    }
  },
  initFormData: function (payload) {
    const keys = Object.keys(this.data.formData)
    const pickForm = common.pick(payload, keys)
    this.updateFormData(pickForm)
  },
  checkCanSubmit: function () {
    const values = Object.values(this.data.formData)
    const isSubmitEnable = values.every(v => !!v)
    this.setData({
      isSubmitEnable
    })
    return isSubmitEnable
  },
  updateFormData: function (payload) {
    this.setData({
      formData: { ...this.data.formData, ...payload }
    }, this.checkCanSubmit)
  },
  onFormChange: function (e) {
    const key = e.currentTarget.dataset.key
    this.updateFormData({ [key]: e.detail.value })
  },
  onConfirm: function () {
    if (!this.data.isSubmitEnable) return;
    if (!validate.isIdCard(this.data.formData.idNo)) {
      common.showToast('请输入正确的身份证号!');
      return
    }
    if (!validate.isPhone(this.data.formData.mobile)) {
      common.showToast('请输入正确的手机号!');
      return
    }
    if (!validate.isBankCard(this.data.formData.bankCardNo)) {
      common.showToast('请输入正确的银行卡号!');
      return
    }
    wx.navigateTo({
      url: `/pages/new-store-info/index?payload=${JSON.stringify(this.data.formData)}&edit=${this.data.edit}`
    })
  }
})
